﻿using Abp.Domain.Repositories;
using Abp.UI;
using Microsoft.AspNetCore.Mvc;
using shenghua.Basics.FileSystem;
using shenghua.Basics.FileSystem.Dto;
using shenghua.Order.Orders;
using shenghua.Payment.Payments;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace shenghua.Controllers
{
    [Route("api/[controller]/[action]")]
    public class FileSystemController : shenghuaControllerBase
    {
        private readonly FileSystemManager _fileSystemManager;
        private readonly IRepository<FileItem> _fileItemRepository;

        public FileSystemController(
            FileSystemManager fileSystemManager,
            IRepository<FileItem> fileItemRepository
            )
        {
            _fileSystemManager = fileSystemManager;
            _fileItemRepository = fileItemRepository;
        }
        
        [HttpPost]
        public async Task<List<FileItemDto>> Upload(UploadDto input)
        {
            var user = await GetCurrentUserAsync();

            var files = this.HttpContext.Request.Form.Files.ToList();

            var result = new List<FileItemDto>();
            foreach(var file in files)
            {
                Stream stream = file.OpenReadStream();
                BinaryReader binaryReader = new BinaryReader(stream);
                byte[] bytes = binaryReader.ReadBytes((int)stream.Length);

                var fileItem = await _fileSystemManager.SaveFlie(user, file.FileName, bytes, input.ParentId);
                result.Add(new FileItemDto(fileItem));
            }
            return result;
        }
        
        [HttpPost]
        public async Task<FileItemDto> SaveFile(string fileName)
        {

            var user = await GetCurrentUserAsync();

            var file = this.HttpContext.Request.Form.Files[fileName];

            if (file == null)
            {
                throw new UserFriendlyException("未找到上传的文件");
            }

            Stream stream = file.OpenReadStream();
            BinaryReader binaryReader = new BinaryReader(stream);
            byte[] bytes = binaryReader.ReadBytes((int)stream.Length);

            var fileItem = await _fileSystemManager.SaveFlie(user, file.FileName, bytes);
            return new FileItemDto(fileItem);
        }

        [HttpPost]
        public IQueryable<FileItem> GetFileItemQuery()
        {
            var query = _fileItemRepository.GetAll().Where(r => r.UserId == AbpSession.UserId);

            return query;
        }
        
        [Route("/Resource")]
        [Route("/Resource/{*others}")]
        [HttpGet]
        public async Task<ActionResult> GetResource(string url)
        {
            if (string.IsNullOrWhiteSpace(url))
            {
                url = this.HttpContext.Request.Path;
            }

            string strPath = AppDomain.CurrentDomain.BaseDirectory + url;
            Image img = Image.FromFile(strPath);
            MemoryStream ms = new MemoryStream();
            img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
            return File(ms.ToArray(), "image/png");
        }

        [HttpPost]
        [HttpGet]
        public void Ueditor()
        {
            var context = this.HttpContext;

            Handler action = null;
            switch (context.Request.Query["action"])
            {
                case "config":
                    action = new ConfigHandler(context);
                    break;
                case "uploadimage":
                    action = new UploadHandler(this, new UploadConfig()
                    {
                        AllowExtensions = Config.GetStringList("imageAllowFiles"),
                        PathFormat = Config.GetString("imagePathFormat"),
                        SizeLimit = Config.GetInt("imageMaxSize"),
                        UploadFieldName = Config.GetString("imageFieldName")
                    });
                    break;
                case "uploadscrawl":
                    action = new UploadHandler(this, new UploadConfig()
                    {
                        AllowExtensions = new string[] { ".png" },
                        PathFormat = Config.GetString("scrawlPathFormat"),
                        SizeLimit = Config.GetInt("scrawlMaxSize"),
                        UploadFieldName = Config.GetString("scrawlFieldName"),
                        Base64 = true,
                        Base64Filename = "scrawl.png"
                    });
                    break;
                case "uploadvideo":
                    action = new UploadHandler(this, new UploadConfig()
                    {
                        AllowExtensions = Config.GetStringList("videoAllowFiles"),
                        PathFormat = Config.GetString("videoPathFormat"),
                        SizeLimit = Config.GetInt("videoMaxSize"),
                        UploadFieldName = Config.GetString("videoFieldName")
                    });
                    break;
                case "uploadfile":
                    action = new UploadHandler(this, new UploadConfig()
                    {
                        AllowExtensions = Config.GetStringList("fileAllowFiles"),
                        PathFormat = Config.GetString("filePathFormat"),
                        SizeLimit = Config.GetInt("fileMaxSize"),
                        UploadFieldName = Config.GetString("fileFieldName")
                    });
                    break;
                case "listimage":
                    action = new ListFileManager(this, Config.GetString("imageManagerListPath"), Config.GetStringList("imageManagerAllowFiles"));
                    break;
                case "listfile":
                    action = new ListFileManager(this, Config.GetString("fileManagerListPath"), Config.GetStringList("fileManagerAllowFiles"));
                    break;
                //case "catchimage":
                //    action = new CrawlerHandler(context);
                //    break;
                default:
                    action = new NotSupportedHandler(this.HttpContext);
                    break;
            }
            action.Process();
        }
    }
}
